﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Scanner.Eth
{
    static class pri_rpc
    {
        //[ThreadStatic]
        static Nethereum.Geth.Web3Geth web3 = null;

        public static void Init()
        {
            //以太坊爬虫核心测试
            var url = "http://127.0.0.1:8545";
            //var url = "https://bsc-dataseed2.defibit.io/";

            if (web3 == null)
                web3 = new Nethereum.Geth.Web3Geth(url);


        }
        public static async Task<int> GetBlockCountAsync()
        {
            Init();

            var sync = await web3.Eth.Syncing.SendRequestAsync();
            if (sync.IsSyncing == false)
            {
                return 12853484;
            }
            var v = int.Parse(sync.CurrentBlock.ToString());
            return v;
        }
        public static async Task<int> GetHeightAsync()
        {
            Init();
            var sync = await web3.Eth.Syncing.SendRequestAsync();
            if (sync.IsSyncing == false)
            {
                return 12853484;
            }
            var v = int.Parse(sync.HighestBlock.ToString());
            return v;
        }
        static int misscount = 0;
        public static async Task<int> GetBlockAsync(uint blockindex, Dictionary<string, bool> addrs, List<string> lines)
        {
            Init();
            Nethereum.Hex.HexTypes.HexBigInteger blockid = new Nethereum.Hex.HexTypes.HexBigInteger(blockindex);
            DateTime t0 = DateTime.Now;
            var block = await web3.Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync(blockid);
            DateTime t1 = DateTime.Now;
            var delta = (t1 - t0).TotalMilliseconds;
            if (block == null)
            {
                Console.WriteLine("=========miss block=" + blockindex + " count=" + misscount);

                misscount++;
                if (misscount > 10)
                    System.Diagnostics.Debugger.Break();
                return 0;
            }
            int length = block.Transactions.Length;
            if (length == 0)
                return 0;
            for (var i = 0; i < length; i++)
            {
                var addr = block.Transactions[i].To;
                if (addr == null)
                    continue;
                if (addrs.ContainsKey(addr))
                    continue;
                addrs[addr] = true;
                lines.Add(addr);
            }
            DateTime t2 = DateTime.Now;
            var delta2 = (t2 - t1).TotalMilliseconds;
            return length;
        }
        public async static void Test()
        {
            Console.WriteLine("test ETH RPC");
            Init();

            Console.WriteLine("c=" + await GetBlockCountAsync());

        }
    }
}
